$.ajaxSetup({
    cache: false
});
(function ($) {
    //提示
    $.duxTips = function (type, msg) {
            Do.ready('notify', function () {
                switch (type) {
                case 'success':
                    UIkit.notify("<i class='uk-icon-check'></i> " + msg, {
                        status: 'success',
                        timeout: 2000
                    });
                    break;
                case 'refresh':
                    UIkit.notify("<i class='uk-icon-check'></i> " + msg + " 页面重载中...", {
                        status: 'success',
                        timeout: 2000
                    });
                    break;
                case 'wait':
                    UIkit.notify("<i class='uk-icon-spinner uk-icon-spin'></i> " + msg + '中，请稍等...', {
                        status: 'warning',
                        timeout: 500
                    });
                    break;
                case 'failure':
                    UIkit.notify("<i class='uk-icon-times-circle'></i> " + '失败：' + msg, {
                        status: 'danger',
                        timeout: 3000
                    });
                    break;
                case 'close':
                    UIkit.notify.closeAll;
                    break;
                default:
                    return false;
                }
            });
        }

    //弹窗
    $.fn.duxFrame = function (options) {
        var defaults = {
            width : '',
            height : '',
            title : '消息'
        }
        var options = $.extend(defaults, options);
        var the = this;
        Do.ready('dialog', function () {
            the.each(function () {
                $(this).click(function () {
                    options = $.extend(options, $(this).data());
                    layer.open({
                        shift : 2,
                        type: 2,
                        title: options.title,
                        shadeClose: true,
                        area: [options.width + 'px', options.height + 'px'],
                        content: options.url
                    });
                });
            });
        });
    }

    //表格处理
    $.fn.duxTable = function (options) {
        var defaults = {
            statusUrl : '',
            deleteUrl : '',
            batchUrl : ''
        }
        var options = $.extend(defaults, options);
        var the = this;
        Do.ready('notify', 'dialog', function () {
            the.each(function () {
                var table = this;
                //处理AJAX动作
                $(table).find('.js-action').click(function () {
                    var obj = this,
                    url = $(obj).data('url'),
                    type = $(obj).data('type'),
                    ask  = $(obj).data('ask'),
                    refresh = $(obj).data('refresh'),
                    data = { id: $(obj).data('id'), field: $(obj).data('field'), val: $(obj).data('val')},
                    title = $(obj).attr('title');
                    var success = function(){},failure = function(){};
                    switch(type) {
                        case "status":
                            if(url == '' || url== null || url == 'undefined'){
                                url = options.statusUrl;
                            }
                            //状态更改
                            if (data.val == 1) {
                                var status = 0;
                                var css = 'uk-text-success';
                            } else {
                                var status = 1;
                                var css = 'uk-text-danger';
                            }
                            ask = false;
                            refresh = false;
                            success = function(){
                                $(obj).removeClass('uk-text-success uk-text-danger');
                                $(obj).addClass(css);
                                $(obj).data('val', status);
                            }
                          break;
                        case "del":
                            //删除
                            if (url == '' || url == null || url == 'undefined') {
                                url = options.deleteUrl;
                            }
                            ask = true;
                            refresh = false;
                            success = function(){
                                $(obj).parents('tr').remove();
                            }
                          break;
                        case "ajax":
                        default:
                          //普通提交
                          break;
                    }
                    if(ask){
                        askPost(refresh, success, failure);
                    }else{
                        ajaxPost(refresh, success, failure);
                    }
                    //提示框
                    function askPost(refresh, success, failure){
                        layer.confirm('请确认' + title + '操作？', {
                            btn: ['确定','取消'],
                            shift : 2
                        }, function(){
                            ajaxPost(refresh, success, failure);
                        }, function(){

                        });
                    }
                    //ajax操作
                    function ajaxPost(refresh, success, failure){
                        $.post(url, data, function (json) {
                            if (json.status) {
                                success(json);
                                if(refresh){
                                    $.duxTips('refresh', json.info);
                                    setTimeout("window.location.reload();", 2000);
                                }else{
                                    $.duxTips('success', json.info);
                                }
                            } else {
                                failure(json);
                                $.duxTips('failure', json.info);
                            }
                        }, 'json').error(function (e, error, msg) {
                            $.duxTips('failure', '内部服务错误');
                        });
                        layer.closeAll();
                    }
                });

                //处理多选
                $(table).find('.js-select-all').click(function () {
                    if ($(this).is(':checked')) {
                        $('.js-select').prop("checked", true);
                    } else {
                        $('.js-select').prop("checked", false);
                    }
                    var num = $(".js-select:checked").length;
                    if (num > 0) {
                        $(table).find('.js-menu').show();
                    } else {
                        $(table).find('.js-menu').hide();
                    }
                });
                //处理单选
                $(table).find('.js-select').click(function () {
                    var num = $(".js-select:checked").length;
                    if (num > 0) {
                        $(table).find('.js-menu').show();
                    } else {
                        $(table).find('.js-menu').hide();
                    }
                });
                //处理批量操作
                $(table).find('.js-batch').click(function () {
                    var ids = new Array();
                    $(table).find(".js-select:checked").each(function () {
                        ids.push($(this).val());
                    });
                    if (ids.length == 0) {
                        $.duxTips('failure', '请选选择操作项目');
                        return false;
                    }
                    var url = $(this).data('url');
                    if (url == '' || url == null || url == 'undefined') {
                        url = options.batchUrl;
                    }
                    var type = $(this).data('type');
                    $.post(url, {
                        ids: ids,
                        type: type
                    }, function (json) {
                        if (json.status) {
                            $.duxTips('refresh', json.info);
                        } else {
                            $.duxTips('failure', json.info + '重载中...');
                        }
                        setTimeout("window.location.reload();", 2000);
                    }, 'json').error(function (e, error, msg) {
                        $.duxTips('failure', '内部服务错误');
                    });
                });
                //处理DIALOG
                $(table).find('.js-dialog').click(function () {
                    var width = '640px', height = '480px';
                    if($(this).data('width')){
                        width = $(this).data('width') + 'px';
                    }
                    if($(this).data('height')){
                        height = $(this).data('height') + 'px';
                    }
                    layer.open({
                        shift : 2,
                        type: 2,
                        title: $(this).data('title'),
                        shadeClose: true,
                        area: [width, height],
                        content: $(this).data('url')
                    });
                });
            });
        });
    };

    //表单处理
    $.fn.duxForm = function (options) {
        var defaults = {
            returnFun: {}
        }
        var options = $.extend(defaults, options);

        var the = this;
        Do.ready('form', 'tooltip', 'password', 'dialog', function () {
            the.each(function () {
                //表单提交
                var form = this;
                $(form).Validform({
                    ajaxPost: true,
                    postonce: true,
                    tiptype: function (msg, o, cssctl) {
                        if (!o.obj.is("form")) {
                            //设置提示信息
                            var objtip = o.obj.siblings(".uk-form-help-inline");
                            if (o.type == 3) {
                                //未通过
                                $.duxTips('failure', msg);

                                var className = 'uk-form-danger';
                            }
                            //设置样式
                            o.obj.removeClass('uk-form-danger');
                            o.obj.addClass(className);
                        }
                    },
                    beforeSubmit:function(curform){
                        //禁用按钮
                        $(form).find(':submit').attr({"disabled":"disabled"});
                        $(form).find(':submit').prepend('<i class="uk-icon-spinner uk-icon-spin"></i> ');
                        $(form).find(':reset').attr({"disabled":"disabled"});
                    },
                    callback: function (data) {
                        $.duxTips('close');
                        if (data.status == 1) {
                            //成功返回
                            if ($.isFunction(options.returnFun)) {
                                options.returnFun(data);
                            } else {
                                if (data.url == null || data.url == '') {
                                    //不带连接
                                    $.duxTips('refresh', data.info);
                                    setTimeout("window.location.reload();", 2000);
                                } else {
                                    //带连接
                                    layer.confirm(data.info, {
                                        btn: ['确定','取消'],
                                        shade: false,
                                    }, function(){
                                        window.location.href = data.url;
                                    }, function(){
                                        window.location.reload();
                                    });
                                }
                            }
                        } else {
                            //失败返回
                            $(form).find(':submit').removeAttr('disabled');
                            $(form).find(':submit').find('i').remove();
                            $(form).find(':reset').removeAttr('disabled');
                            $.duxTips('failure', data.info);
                        }
                    }
                });
            });
        });
    };

    //编辑器
    $.fn.duxEditor = function (options) {
        var defaults = {};
        var options = $.extend(defaults, options);
        var the = this;
        Do.ready('ueditor', function () {
            the.each(function () {
                id = $(this).attr('id');
                var str = id + ' = UE.getEditor(id);';
                eval(str);
            });
        });
    };

    //时间插件
    $.fn.duxTime = function (options) {
        var defaults = {
            format: 'YYYY/MM/DD hh:mm:ss',
            istime: true,
            istoday: true
        };
        var options = $.extend(defaults, options);
        var the = this;
        Do.ready('time', function () {
            the.each(function () {
                $(this).unbind('click').click(function () {
                    options = $.extend(options, $(this).data());
                    laydate(options);
                });
            });
        });
    };

    //图片预览调用
    $.fn.duxImage = function () {
        var the = this;
        Do.ready('lightbox', function () {
            the.each(function () {
                var obj = this;
                $(this).unbind('click').click(function () {
                    var img = $($(this).data('target')).val();
                    if(!img){
                        alert('请先上传图片！');
                        return;
                    }
                    var lightbox = UIkit.lightbox.create([
                        {
                            'source': img,
                            'type': 'image'
                            }
                    ]);
                    lightbox.show();
                });
            });
        });
    };

    //上传调用
    $.fn.duxFileUpload = function (options) {
        var defaults = {
            url: rootUrl + 'system/SystemUpload/index.html',
            type: '*',
            params: {},
            complete: function () {}
        }
        var options = $.extend(defaults, options);
        var the = this;
        Do.ready('dialog', 'upload', function () {
            the.each(function () {
                //其他参数
                var id = $(this).attr('id'),
                    uploadId = 'upload_' + id,
                    selectId = 'select_' + id,
                    barId = 'bar_' + id,
                    html = '<div id="' + uploadId + '" class=" uk-placeholder uk-text-center uk-form-file">\
                        <i class="uk-icon-cloud-upload uk-icon-medium uk-text-muted uk-margin-small-right"></i> 将文件拖拽至此 或 点击选择文件<input id="' + selectId + '" type="file" multiple></span>\
                        </div>\
                    <div id="' + barId + '" class="uk-progress uk-hidden">\
                        <div class="uk-progress-bar" style="width: 0%;">0%</div>\
                    </div>';
                $(this).unbind('click').click(function () {
                    var button = this;
                    layer.open({
                        type: 1,
                        shift : 2,
                        title : '上传',
                        content: html //这里content是一个普通的String
                    });

                    //合并参数
                    options = $.extend(options, $(this).data());
                    var params = options.params;
                    var progressbar = $("#" + barId),
                        bar = progressbar.find('.uk-progress-bar'),
                        settings = {
                            action: options.url,
                            allow: '*.(' + options.type + ')',
                            type: 'json',
                            params: params,
                            loadstart: function () {
                                bar.css("width", "0%").text("0%");
                                progressbar.removeClass("uk-hidden");
                            },
                            progress: function (percent) {
                                percent = Math.ceil(percent);
                                bar.css("width", percent + "%").text(percent + "%");
                            },
                            complete: function (data) {
                                if (data.status) {
                                    if(options.target == ''){
                                        var target = $(options.target);
                                    }else{
                                        var target =$(button).prev();
                                    }
                                    target.val(data.data.url);
                                    options.complete(data.data);
                                } else {
                                    $.duxTips('failure', data.info);
                                    return false;
                                }
                            },
                            allcomplete: function (data) {
                                bar.css("width", "100%").text("100%");
                                setTimeout(function () {
                                    progressbar.addClass("uk-hidden");
                                }, 250);
                                layer.closeAll();
                                $.duxTips('success', '上传处理完毕！');
                            }
                        };
                    var select = UIkit.uploadSelect($("#" + selectId), settings),
                        drop = UIkit.uploadDrop($("#" + uploadId), settings);
                });
            });
        });
    };

    //组图上传
    $.fn.duxMultiUpload = function (options) {
        var defaults = {
            url: '',
            params: {},
        }
        var options = $.extend(defaults, options);
        var the = this;
        Do.ready('sortable', 'lightbox', function () {
            the.each(function () {
                var id = $(this).attr('id'),
                    sortableId = '#' + id + '_sortable';
                //绑定上传
                $('#' + id).duxFileUpload({
                    url: options.url,
                    type: 'jpg|png|bmp|gif|jpeg',
                    params: options.params,
                    complete: function (data) {
                        var html = '<li>\
                            <div class="uk-thumbnail">\
                                <figure class="uk-overlay uk-overlay-hover uk-text-center">\
                                <img src="' + data.url + '" width="150" height="100" alt="">\
            <figcaption class="uk-overlay-panel uk-overlay-background uk-overlay-bottom"><a class="uk-button uk-button-primary uk-button-small image-preview">预览</a> <a class="uk-button uk-button-danger uk-button-small image-del"  href="javascript:;">删除</a></figcaption>\
                                </figure>\
                                <div class="uk-thumbnail-caption">' + data.title + '</div>\
                            </div>\
                            <input type="hidden" name="' + id + '[url][]" value="' + data.url + '">\
                            <input type="hidden" name="' + id + '[title][]" value="' + data.title + '">\
                        </li>';
                        $(sortableId).append(html);
                    }
                });
                //绑定删除
                $(sortableId).on('click', '.image-del', function () {
                    $(this).parents('li').remove();
                });
                //绑定预览
                $(sortableId).on('click', '.image-preview', function () {
                    var lightbox = UIkit.lightbox.create([
                        {
                            'source': $(this).parents('li').find('img').attr('src'),
                            'type': 'image'
                        }
                    ]);
                    lightbox.show();
                });
            });

        });
    };

    //表单页面处理
    $.fn.duxFormPage = function (options) {
        var defaults = {
            uploadUrl: rootUrl + 'system/SystemUpload/index.html',
            formReturnFun: {},
            form: true
        }
        var options = $.extend(defaults, options);
        this.each(function () {
            var form = this;
            form = $(form);
            //表单处理
            if (options.form) {
                form.duxForm({
                    returnFun: options.formReturnFun
                });
            }
            //文件上传
            if (form.find(".js-file-upload").length > 0) {
                form.find('.js-file-upload').duxFileUpload({
                    type: '*',
                    url: options.uploadUrl
                });
            }
            //图片上传
            if (form.find(".js-img-upload").length > 0) {
                form.find('.js-img-upload').duxFileUpload({
                    type: 'jpg|png|gif|bmp|jpeg',
                    url: options.uploadUrl
                });
            }
            //图片预览
            if (form.find(".js-image").length > 0) {
                form.find('.js-image').duxImage();
            }
            //多图片上传
            if (form.find(".js-multi-upload").length > 0) {
                form.find('.js-multi-upload').duxMultiUpload({
                    type: 'jpg|png|gif|bmp|jpeg',
                    url: options.uploadUrl
                });
            }
            //编辑器
            if (form.find(".js-editor").length > 0) {
                form.find('.js-editor').duxEditor();
            }
            //时间选择
            if (form.find(".js-time").length > 0) {
                form.find('.js-time').duxTime();
            }
        });
    };

    // 无限级连动插件[全国省市县]
    $.fn.Linkage = function(o){
        o = $.extend({url:'',selects:['#province','#city','#county'],initRunCallBack:false,selected:['0','0','0']}, o || {});
        var url = o.url;
        var arrNodeChild = new Array();
        var arrSelect = o.selected;
        var options = new Array();
        $.each(arrSelect,function(i){
            options[i] = '';
        });
        var len = o.selects.length;
        for(var i=0;i<len;i++) arrNodeChild[i] = new Array();
        //请求格式化后的JSON数据
        $.post(o.url,function(data){
            $.each(data, function(i, n){
                var c_id = i.substr(2);
                var selected = (c_id == arrSelect[0]) ? 'selected="selected"' : '';
                options[0] += '<option value="' + c_id + '" ' + selected + '>' + n.t + '</option>';
                
                n.id = c_id;
                if(n.c !== null){
                    arrNodeChild[0][i] = n.c;
                    parse(n,0);
                }
            });
            
            $.each(o.selects,function(i,em){
                $(em).append(options[i]);
            });
            if(o.initRunCallBack)callback();
        },"json");
        //解析每一层元素
        function parse(data,num){
            if(data.c !==undefined && data.c !== null) {
                $.each(data.c, function(i, n) {
                    var c_id = i.substr(2);
                    if(data.id == arrSelect[num]) {
                        var selected = (c_id == arrSelect[num+1]) ? 'selected="selected"' : '';
                        options[num+1] += '<option value="' + c_id + '" ' + selected + '>' + n.t + '</option>';
                    }
                    n.id = c_id;
                    arrNodeChild[num+1][i] = n.c;
                    if(n.c !== null) parse(n,num+1);
                });
            }
        }
        //回调处理
        function callback()
        {
            if(typeof(o.callback) == 'function'){
                var selected =new Array(); value =new Array(); text = new Array();
                $.each(o.selects,function(i,em){
                    value[i] = $(em).val();
                    text[i] = $('option:selected',$(em)).text();
                });
                selected[0] = value;
                selected[1] = text;
                o.callback(selected);
            }
        }
        //逐级绑定连动事件
        var len = o.selects.length;
        $.each(o.selects,function(i,em){
            $(em).change(function(){
                var val = 'o_'+$(this).val();
                if(arrNodeChild[i][val] !== null && i<len-1) {

                    for(var j=i+1 ; j<len ;j++){
                        var option = $(o.selects[j]).children().first();
                        if(option.val()==0)$(o.selects[j]).empty().append(option);
                        else $(o.selects[j]).empty().append("<option value='0'>请选择</option>");
                    }
                    if(val != 0){
                        var select = '';
                        if(arrNodeChild[i][val]!==undefined){
                            $.each(arrNodeChild[i][val], function(k, n) {
                            var c_id = k.substr(2);

                            select += '<option value="' + c_id + '">' + n.t + '</option>';
                        });
                        $(o.selects[i+1]).append(select);
                        }
                        
                    }
                }
                callback();
            });
        });
    };  


})(jQuery);